import { ref } from "vue";
import { type LoginRes, type EmplInfo2, type ServiceYearCalcRes } from "./api";
import * as XLSX from 'xlsx';

export const selectOrg = ref<string>('');

export const selectEmpl = ref<EmplInfo2>({
    account: '',
    name: '',
    org: '',
    job: '',
    date: '',
    holiday: 0,
    active: 0,
});

export const TIMES = [
	'上午',
	'下午',
	'前半夜',
	'后半夜',
];

export const userInfo = ref<LoginRes>({
    session: {
        user: {
            id: 0,
            name: '',
            account: '',
            pwd: ''
        },
        perms: [],
        login_invalid_timestamp: 0,
    },
    key: '',
});

export function dateFormat(date: Date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}-${month}-${day}`;
}

export function exportXlsx<T>(json: T[], name: string) {
    const wb = XLSX.utils.book_new();
    const sheet = XLSX.utils.json_to_sheet(json);
    XLSX.utils.book_append_sheet(wb, sheet, "Sheet1");
    const blob = XLSX.write(wb, {
        bookType: 'xlsx',
        type: 'buffer',
    });
    saveFile(blob, name);
}

function saveFile(blob: any, fileName: string) {
    const link = document.createElement('a');
    link.href = URL.createObjectURL(new Blob([blob], {
        type: 'application/octet-stream'
    }));
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

export function activeHolidayIndex(info: ServiceYearCalcRes) {
    if (info.holiday.current_holiday == null) {
        return null;
    }
    let current = info.holiday.current_holiday;
    for (let i = 0; i < info.holiday.holiday_parts.length; i ++) {
        let item = info.holiday.holiday_parts[i];
        if ((item.holiday.begin_date == current.holiday.begin_date)) {
            return i;
        }
    }
    return null;
}

export function activeColor(info: ServiceYearCalcRes, index: number) {
    let v = activeHolidayIndex(info);
    if (v == index) {
        return 'rgb(64,158,255)';
    }
    return 'gray';
}



